if arg[2] == "debug" then
    require("lldebugger").start()
end
local love_errorhandler = love.errhand
local Tabledump = require("Tabledump")
local Enemy = require "Enemy"
local Tower = require "Tower"
local Fireball = require "Fireball"
local FireArea = require "FireArea"

-- main.lua
local BattleMapConfig = require("BattleMapConfig")
local BattleMap = require("BattleMap")
local BattleConst = require("BattleConst")
local BattleType = require("BattleConst").BattleType

local enemies = {}
local towers = {}
-- 火焰弹
local fireballs = {}
-- 火焰区域
local fireAreas = {}
local wave = 1
local enemySpawnTimer = 0 --生成敌人时间间隔
local playeronescore =0
local playertwoscore =0
local battleMap = {}
-- 屏幕中心点的 左边转换为0，0
local difx =320+30  --700-640的差值
local dify =320+30

local cellWidth =88 --地图塔块的宽
local cellheight =74 --地图塔块的高
local isoknew =false
local fixedposnew = { x = 0, y = 0}
local fixedindexnew = 0
local oldfixedpos = { x = 0, y = 0}
local oldfixedindex = 0

local buttonnew =1
local tempkey =0
local incTowerid =0   --塔编号自增

local incEnmeyid =0   --怪编号自增

-- 记录当前帧塔攻击怪物的数据
local collectAttackData = {}

local countdown = 5  -- 倒计时设置为5秒
local startBattle = false --来控制是否开始战斗。
local waveNumber = 0    --波数
local spawnInterval = 60  -- 每波间隔60秒
local timeSinceLastWave = 0 --用于记录自上次生成波的时间。
-- 游戏状态变量
local speedMultiplier = 1  -- 速度倍数
 -- 配置波数参数
local waves = {
    {interval = 20, initenemyCount = 20, enemyCount = 0},  -- 第1波
    {interval = 20, initenemyCount = 20, enemyCount = 0},  -- 第2波
    {interval = 20, initenemyCount = 20, enemyCount = 0},  -- 第3波
}
local testtime =0
-- 快速敌人类
local FastEnemy = setmetatable({}, Enemy)
FastEnemy.__index = FastEnemy

function FastEnemy:new(side)
    local enmeyid =0
    incEnmeyid =incEnmeyid +1
    enmeyid =incEnmeyid
    return Enemy.new(self, side,1,enmeyid, 40, 200) -- 20生命，5速度
end

-- 重型敌人类
local HeavyEnemy = setmetatable({}, Enemy)
HeavyEnemy.__index = HeavyEnemy

function HeavyEnemy:new(side)
    local enmeyid =0
    incEnmeyid =incEnmeyid +1
    enmeyid =incEnmeyid
    return Enemy.new(self,  side,2,enmeyid, 100, 100) -- 50生命，2速度
end

-- 说明
-- 基塔类 (Tower)：定义了通用的塔属性和方法。
-- 不同类型塔：
-- 弓箭塔 (ArcherTower)：远程攻击，较长的攻击范围和较快的攻击速度。
-- 火焰塔 (FlameTower)：范围较小但输出较高的攻击。
-- 基敌人类 (Enemy)：定义了通用的敌人属性和方法。
-- 不同类型敌人：
-- 快速敌人 (FastEnemy)：速度快，但生命值低。
-- 重型敌人 (HeavyEnemy)：生命值高，但速度慢。
-- 定义路径
local paths = {
    -- { {x = 50, y = 50}, {x = 50, y = 350}, {x = 650, y = 350}, {x = 650, y = 50} },
    { {x = difx-320, y = dify-320}, {x = difx-320, y = dify+0}, {x = difx+320, y = dify+0}, {x = difx+320, y =  dify-320} },
    { {x = difx-320, y = dify+320}, {x = difx-320, y = dify+0}, {x = difx+320, y = dify+0}, {x = difx+320, y = dify+320} }
}
-- 弓箭塔类
local ArcherTower = setmetatable({}, Tower)
ArcherTower.__index = ArcherTower

function ArcherTower:new(x, y, side,fixedindex)
    local towerid =0
    incTowerid =incTowerid +1
    towerid =incTowerid
    return Tower.new(self, x, y, side,fixedindex,1,towerid,150, 3, 2) -- ,塔类型，塔编号， 150范围，3伤害，2攻击速度
end

-- 火焰塔类
local FlameTower = setmetatable({}, Tower)
FlameTower.__index = FlameTower

function FlameTower:new(x, y, side,fixedindex)
    local towerid =0
    incTowerid =incTowerid +1
    towerid =incTowerid
    return Tower.new(self, x, y,side,fixedindex, 2,towerid, 100, 5, 3) -- 塔类型，塔编号，100范围，5伤害，3攻击速度
end



function love.load()
    love.window.setTitle("Lua Tower Defense")
    love.window.setMode(700, 700)
    battleMap = BattleMap.new(self,BattleType.COOP) 
    -- -- 要写入文件的内容
    -- local data = {
    --     name = "Tower Defense",
    --     level = 1,
    --     towers = {
    --         {type = "sniper", x = 100, y = 150},
    --         {type = "rapid", x = 200, y = 250}
    --     }
    -- }
    
    -- saveTableToFile(data)
end
function love.errorhandler(msg)
    if lldebugger then
        error(msg, 2)
    else
        return love_errorhandler(msg)
    end
end

function love.update(dt)


    if not startBattle then
        countdown = countdown - dt* speedMultiplier
        if countdown <= 0 then
            startBattle = true
            print("战斗开始！")

        end
    else
        timeSinceLastWave = timeSinceLastWave + dt* speedMultiplier
        if waveNumber  < 1 or (waveNumber < #waves and timeSinceLastWave >= waves[waveNumber + 1].interval) then

            waveNumber = waveNumber + 1
            print("战斗开始，波数: " .. waveNumber)
            timeSinceLastWave = 0  -- 重置计时器
            startBattle =false
        else
            -- 第80波后不再出怪 这里判断游戏结束
        end
        if startBattle then
            enemySpawnTimer = enemySpawnTimer + dt* speedMultiplier
            if enemySpawnTimer > 0.5    and waves[waveNumber].initenemyCount > waves[waveNumber].enemyCount then -- 每秒生成一个敌人
                -- and  #enemies < 2
                spawnEnemy()
                enemySpawnTimer = 0
            end
            
        end


    end
    -- 每帧塔攻击怪物的数据都需要清空
    collectAttackData ={}
    -- 更新敌人位置
    local tempfps =dt* speedMultiplier
    for _, enemy in ipairs(enemies) do
        enemy:update(tempfps)
    end

    -- 添加附近塔效果
    for _, tower in ipairs(towers) do
        tower:applyEffect(towers) -- 应用效果到所有塔
    end
    -- 更新塔
    for _, tower in ipairs(towers) do
        tower:update(enemies, tempfps,collectAttackData,fireballs)
    end
    -- if #collectAttackData then
    --     -- 要写入文件的内容
    --     local serializedTable = serializeTable(collectAttackData)

    --     appendToFile( serializedTable)
    -- end
    --         -- 要写入文件的内容
    -- local serializedTable = serializeTable(towers)

    -- appendToFile( serializedTable)

    -- for i, enemy in ipairs(enemies) do
    --     enemy.y = enemy.y + enemy.speed * dt
    --     if enemy.y > love.graphics.getHeight() then
    --         table.remove(enemies, i) -- 敌人到达底部，移除
    --     end
    -- end
    updateFireballs(tempfps, enemies)
    updateFireAreas(tempfps, enemies)
    -- 要写入文件的内容
    local serializedTable = serializeTable(fireballs)

    appendToFile( serializedTable)
    -- 移除死亡的敌人
    for i = #enemies, 1, -1 do
        if not enemies[i].alive then
            if enemies[i].deadbyside ==1 then
                playeronescore  =playeronescore  +1
            else
                playertwoscore   =playertwoscore  +1
            end
            table.remove(enemies, i)
        end
    end
    
    -- for _, tower in ipairs(towers) do
    --     attack(tower,enemies)
    -- end
    
end
function appendToFile( content)
    -- 检查文件是否存在

    local filename = "output.txt"
    if love.filesystem.getInfo(filename) then
        -- 读取现有内容
        local existingContent = love.filesystem.read(filename)
        -- 合并内容
        content = existingContent .. content
    end
    -- 使用 love.filesystem 来写入文件
    love.filesystem.write(filename, content)
end
function serializeTable(tbl, indent)
    indent = indent or 0
    local toWrite = {}
    local prefix = string.rep("  ", indent)
    
    table.insert(toWrite, "{\n")
    for k, v in pairs(tbl) do
        local key = type(k) == "string" and string.format("%q", k) or k
        if type(v) == "table" then
            table.insert(toWrite, string.format("%s[%s] = %s,\n", prefix .. "  ", key, serializeTable(v, indent + 1)))
        else
            local value = type(v) == "string" and string.format("%q", v) or tostring(v)
            table.insert(toWrite, string.format("%s[%s] = %s,\n", prefix .. "  ", key, value))
        end
    end
    table.insert(toWrite, prefix .. "}")
    
    return table.concat(toWrite, "")
end

function saveTableToFile(tbl)
    local serializedTable = serializeTable(tbl)
        -- 要写入文件的内容
        local content = serializedTable
    
        -- 使用 love.filesystem 来写入文件
        local success, err = love.filesystem.write("output.txt", content)
end
local playerOneRange = { x = 80, y = 80, w = 560, h = 260 }
local playerTwoRange = { x = 80, y = 380, w = 560, h = 260 }
function love.draw()
     -- 绘制地面火焰
     for _, fireArea in ipairs(fireAreas) do
        love.graphics.setColor(1, 0.3, 0)
        love.graphics.circle("fill", fireArea.x, fireArea.y, 20)
    end
    love.graphics.setColor(1, 0, 0) -- 红色
    for _, enemy in ipairs(enemies) do
        if enemy.side ==1 then
            if enemy.enmeyType ==1 then
                love.graphics.setColor(1, 0, 0) -- 红色
                love.graphics.rectangle("fill", enemy.x-10, enemy.y-10, 20, 20)
                love.graphics.setColor(1, 1, 0) -- 黄色
                love.graphics.printf(enemy.health..".."..enemy.speed,  enemy.x-10, enemy.y-10, 75, "left" )
            else
                love.graphics.setColor(1, 1, 0) -- 黄色
                love.graphics.rectangle("fill", enemy.x-10, enemy.y-10, 20, 20)
                love.graphics.setColor(1, 0, 0) -- 红色
                love.graphics.printf(enemy.health..".."..enemy.speed,  enemy.x-10, enemy.y-10, 75, "left" )
            end
        else
            if enemy.enmeyType ==1 then
                love.graphics.setColor(1, 0, 0) -- 红色
                love.graphics.rectangle("fill", enemy.x-10, enemy.y-10, 20, 20)
                love.graphics.setColor(1, 1, 0) -- 黄色
                love.graphics.printf(enemy.health..".."..enemy.speed,  enemy.x-10, enemy.y-10, 75, "left" )
            else
                love.graphics.setColor(1, 1, 0) -- 黄色
                love.graphics.rectangle("fill", enemy.x-10, enemy.y-10, 20, 20)
                love.graphics.setColor(1, 0, 0) -- 红色
                love.graphics.printf(enemy.health..".."..enemy.speed,  enemy.x-10, enemy.y-10, 75, "left" )
            end
        end
    end

    for _, tower in ipairs(towers) do
        if tower.towerType ==1 then
            local sameFixedindexTowers =findSameFixedindexTowers(tower.fixedindex,tower.side)
            if #sameFixedindexTowers >2 then
                love.graphics.setColor(0, 1, 1) -- 3塔  火焰塔类
                love.graphics.rectangle("fill", tower.x-15, tower.y-15, 30, 30)
             
            end
            if #sameFixedindexTowers >1 then
                love.graphics.setColor(0, 1, 0) -- 2塔 火焰塔类
                love.graphics.rectangle("fill", tower.x-10, tower.y-10, 20, 20)
             
            end
            if #sameFixedindexTowers then
                love.graphics.setColor(0, 0, 1) -- 1塔 火焰塔类
                love.graphics.rectangle("fill", tower.x-5, tower.y-5, 10, 10)
           
            end
            love.graphics.setColor(255, 255, 255) 
            -- love.graphics.printf(tower.side,  tower.x-10, tower.y-10, 75, "left" )
            love.graphics.printf(tower.towerid,  tower.x-10, tower.y-10, 75, "left" )
            -- love.graphics.printf(tower.x.."_"..tower.y,  tower.x-10, tower.y-10, 75, "left" )
            love.graphics.setColor(255, 255, 255) -- 白色
            love.graphics.circle("line",tower.x,tower.y,tower.range)

        else
       
            local sameFixedindexTowers =findSameFixedindexTowers(tower.fixedindex,tower.side)
            if #sameFixedindexTowers >2 then
                love.graphics.setColor(1, 1, 1) -- 3塔  火焰塔类
                love.graphics.rectangle("fill", tower.x-15, tower.y-15, 30, 30)
             
            end
            if #sameFixedindexTowers >1 then
                love.graphics.setColor(1, 1, 0) -- 2塔 火焰塔类
                love.graphics.rectangle("fill", tower.x-10, tower.y-10, 20, 20)
             
            end
            if #sameFixedindexTowers then
                love.graphics.setColor(1, 0, 1) -- 1塔 火焰塔类
                love.graphics.rectangle("fill", tower.x-5, tower.y-5, 10, 10)
           
            end
            -- love.graphics.printf(tower.side,  tower.x-15, tower.y-15, 75, "left" )
            love.graphics.setColor(255, 255, 255) 
            love.graphics.printf(tower.towerid,  tower.x-10, tower.y-10, 75, "left" )
            -- love.graphics.printf(tower.x.."_"..tower.y,  tower.x-10, tower.y-10, 75, "left" )
            love.graphics.setColor(255, 255, 255) -- 白色
            love.graphics.circle("line",tower.x,tower.y,tower.range)
        end
      
    end
    love.graphics.setColor(1, 0, 0) -- 红色
    love.graphics.printf("totle enemy "..#enemies, 10, 0, 100, "left" )
    -- playeronescore= Tower:getplayeronescore()
    -- playertwoscore= Tower:getplayertwoscore()
    love.graphics.printf("p1   "..playeronescore, 10, 120, 100, "left" )
    love.graphics.printf("p2   "..playertwoscore, 10, 500, 100, "left" )
    -- love.graphics.setColor(255, 0, 255) -- 粉色
    -- love.graphics.rectangle("line",playerOneRange.x,playerOneRange.y,playerOneRange.w,playerOneRange.h)
    -- love.graphics.rectangle("line",playerTwoRange.x,playerTwoRange.y,playerTwoRange.w,playerTwoRange.h)

    -- 塔固定放置位置
    local tfigherPosOne = battleMap:getFighterPosList(1)
    love.graphics.setColor(255, 0, 255) -- 粉色
    for k, fixedposinfo in ipairs(tfigherPosOne) do
        love.graphics.rectangle("line",fixedposinfo.x-cellWidth/2,fixedposinfo.y-cellheight/2,cellWidth,cellheight)
        love.graphics.setColor(1, 0, 0) -- 红色
        -- love.graphics.printf(fixedposinfo.x.." "..fixedposinfo.y,  fixedposinfo.x-cellWidth/2, fixedposinfo.y,100, "left" )
        love.graphics.printf(k,  fixedposinfo.x, fixedposinfo.y,100, "left" )
    end
    local tfigherPosTwo = battleMap:getFighterPosList(2)
    love.graphics.setColor(255, 0, 255) -- 粉色
    for k, fixedposinfo in ipairs(tfigherPosTwo) do
        love.graphics.rectangle("line",fixedposinfo.x-cellWidth/2,fixedposinfo.y-cellheight/2,cellWidth,cellheight)
        love.graphics.setColor(1, 0, 0) -- 红色
        love.graphics.printf(k,  fixedposinfo.x, fixedposinfo.y,100, "left" )
    end
    local x = love.mouse.getX()
    local y = love.mouse.getY()
    love.graphics.setColor(1, 0, 0) -- 红色
    love.graphics.printf(x.."_ "..y, 350, 20, 100, "left" )
    if isoknew then
        love.graphics.printf(tostring(isoknew).."_ "..fixedposnew.x.."_ "..fixedposnew.y.."_ "..fixedindexnew, 20, 20, 100, "left" )
    end
    love.graphics.printf(buttonnew, 350, 40, 100, "left" )

       -- 绘制火焰弹
       for _, fireball in ipairs(fireballs) do
        -- if fireball.active then
            love.graphics.setColor(1, 0.5, 0)
            love.graphics.circle("fill", fireball.x, fireball.y, 2)
        -- end
    end

   
    displayFPS()


end

function love.mousepressed(x, y, button)
    buttonnew =button
    if button == 1 then -- 左键放塔
        
        local chairId =0
    
        if towerIntoPlayerOne(x,y) then
            chairId =1
        end
        if towerIntoPlayerTwo(x,y) then
            chairId =2
        end
        if chairId then
            placeTower(x, y,chairId)
        end
    end
    if button == 2 then -- 右键移除塔
        -- deleteTower(x, y)
        if isoknew then
            -- 玩家的座位号来区分调用
            local tempchairId =1
            local tfigherPos = battleMap:getFighterPosList(tempchairId)
            local isok,fixedpos,fixedindex = checkfixedPositions(tfigherPos,x,y)
            if isok then
                moveTower(oldfixedpos,oldfixedindex,fixedpos,fixedindex,tempchairId)
                isoknew =false
                fixedposnew ={ x = 0, y = 0}
                fixedindexnew =0
            end
        else
            -- 玩家的座位号来区分调用
            local tempchairId =1
            local tfigherPos = battleMap:getFighterPosList(tempchairId)
            local isok,fixedpos,fixedindex = checkfixedPositions(tfigherPos,x,y)
            if isok then
                -- moveTower(x, y,fixedindex)
                isoknew =isok
                oldfixedpos =fixedpos
                oldfixedindex =fixedindex
            end
        end
    end
end

function love.keypressed(key)
    tempkey =key
    if key == 'return' then
        -- 随机上塔
        local chairId =1
        local towerType =math.random(2)
        local fixedindex = findMinSameTypeTowers(towerType)
        local tfigherPos = battleMap:getGridPos(chairId,fixedindex)
        placeTower(tfigherPos.x, tfigherPos.y,chairId)
    elseif key == '1' then
        speedMultiplier = 1  -- 速度倍数
    elseif key == '2' then
        speedMultiplier = 2  -- 速度倍数
    end
end

function spawnEnemy()
    local pathtop =1;
    local pathdown =2;
    local enemyid =math.random(2)

    if enemyid ==1 then 
        -- 快速敌人类
        local enemy  =FastEnemy:new(pathtop)
        waves[waveNumber].enemyCount = waves[waveNumber].enemyCount+1
        table.insert(enemies, enemy)
        local enemytwo  =FastEnemy:new(pathdown)
        waves[waveNumber].enemyCount = waves[waveNumber].enemyCount+1
        table.insert(enemies, enemytwo)
    else
        -- 重型敌人类
        local enemy  =HeavyEnemy:new(pathtop)
        waves[waveNumber].enemyCount = waves[waveNumber].enemyCount+1
        table.insert(enemies, enemy)
        local enemytwo  =HeavyEnemy:new(pathdown)
        waves[waveNumber].enemyCount = waves[waveNumber].enemyCount+1
        table.insert(enemies, enemytwo)
    end
end

function placeTower(x, y,chairId)
    -- // 地图 放置塔
    local tfigherPos = battleMap:getFighterPosList(chairId)
    -- Tabledump.dump( "main gameLoop->", towers)
    local isok,fixedpos,fixedindex = checkfixedPositions(tfigherPos,x,y)
   
    if isok then
        local sameFixedindexTowers =findSameFixedindexTowers(fixedindex,chairId)
        if #sameFixedindexTowers < 3 then
            -- local towerType =math.random(2)
            local towerType =1
            local side =chairId
            if #sameFixedindexTowers==0 or towerType == sameFixedindexTowers[1].towerType  then
                if towerType ==1 then
                    if side >0 then
                        local tower  =ArcherTower:new(fixedpos.x , fixedpos.y , side,fixedindex)
                        table.insert(towers, tower)
                    end
                else
                    if side >0 then
                        local tower  =FlameTower:new(fixedpos.x , fixedpos.y , side,fixedindex)
                        table.insert(towers, tower)
                    end
                
                end
            end
        else
            combineTowers(fixedindex,chairId)
        end
    end

end
-- //玩家1的塔
function  towerIntoPlayerOne(x,y)
    if x>playerOneRange.x and y >playerOneRange.y and x<playerOneRange.x + playerOneRange.w and y<playerOneRange.y +playerOneRange.h then
        return true
    end
    return false
end
-- //玩家2的塔
function  towerIntoPlayerTwo(x,y)
    if x>playerTwoRange.x and y >playerTwoRange.y and x<playerTwoRange.x + playerTwoRange.w and y<playerTwoRange.y +playerTwoRange.h then
        return true
    end
    return false
end


-- //
function  checkintofixedPos(x,y,fx,fy)
    if x>fx-cellWidth/2 and y >fy-cellheight/2 and x<fx+cellWidth/2 and y<fy+cellheight/2 then
        return true
    end
    return false
end
-- 按地图固定位置添加塔
function  checkfixedPositions(tfigherPos,x,y)
    for k, fixedposinfo in ipairs(tfigherPos) do
        local isok = checkintofixedPos(x,y,fixedposinfo.x,fixedposinfo.y)
        if isok then
            return true,fixedposinfo,k
        else
          
        end
    end
    return false,{ x = 0, y = 0 },0
end

function deleteTower(x,y)
    local tfigherPosOne = battleMap:getFighterPosList(1)
    local isok,fixedpos,fixedindex = checkfixedPositions(tfigherPosOne,x,y)
    local tfigherPosTwo = battleMap:getFighterPosList(2)
    local isoktwo,fixedpostwo,fixedindextwo = checkfixedPositions(tfigherPosTwo,x,y)
    for _, tower in ipairs(towers) do
        if isok and tower.x ==fixedpos.x  and tower.y ==fixedpos.y then
            table.remove(towers, _) -- 删除塔
        end
        if isoktwo and tower.x ==fixedpostwo.x  and tower.y ==fixedpostwo.y then
            table.remove(towers, _) -- 删除塔
        end
    end
end
--  移动塔 交换塔
function moveTower(oldfixedpos,oldfixedindex,newfixedpos,newfixedindex,chairId)
    --- 找出 被换位置对应的 塔的信息 
    local towersToSwitch = {}

    local temptowers =clone(towers)
    local newT = {}
    -- 清空原有塔
    for _, tower in ipairs(towers) do
        if tower.fixedindex ==  newfixedindex  and tower.side == chairId then
            table.insert(towersToSwitch, tower)  
        else
            table.insert(newT , tower)
        end
        
    end
    temptowers= newT
    --- 排除掉 被换位置对应的 塔的信息  temptowers
    for _, tower in ipairs(temptowers) do
        if tower.fixedindex ==oldfixedindex then
            tower.x = newfixedpos.x
            tower.y = newfixedpos.y
            tower.fixedindex = newfixedindex
        end
    end
    if towersToSwitch then
        --- 临时被换位置的塔信息 位置交换到 触发位置
        for _, tower in ipairs(towersToSwitch) do
            tower.x = oldfixedpos.x
            tower.y = oldfixedpos.y
            tower.fixedindex = oldfixedindex
            table.insert(temptowers, tower)
        end
    end
    towers= temptowers
 
    print("Tower group moved to: (" .. newfixedpos.x .. ", " .. newfixedpos.y .. ")")
end

function displayFPS()
    love.graphics.setColor(0, 1, 0, 1)
    love.graphics.print('FPS: ' .. tostring(love.timer.getFPS()), 10, 10)
    love.graphics.print('towers: ' .. tostring(#towers), 10, 30)
    love.graphics.print('key: ' .. tostring(tempkey), 10, 50)
    -- 显示倒计时
    if not startBattle then
        love.graphics.print("djs: " .. math.ceil(countdown), 80, 10)
    else
        if waveNumber > 0 then
            -- waves[waveNumber].interval -
            love.graphics.print("djs: " .. math.ceil(  waves[waveNumber].interval -timeSinceLastWave ), 80, 10)
        end
    end
    love.graphics.print("wave: " .. tostring(waveNumber), 80, 30)
end
-- 找出同类型的塔
function findSameTypeTowers(towerType)
    local sameTypeTowers = {}
    for _, tower in ipairs(towers) do
        if tower.towerType  == towerType then
            table.insert(sameTypeTowers, tower)
        end
    end
    return sameTypeTowers
end

-- 找出玩家 同一个固定位置的塔信息 1~3
function findSameFixedindexTowers(fixedindex,chairId)
    local sameFixedindexTowers = {}
    for _, tower in ipairs(towers) do
        if tower.fixedindex  == fixedindex  and tower.side == chairId then
            table.insert(sameFixedindexTowers, tower)
        end
    end
    return sameFixedindexTowers
end
-- 合成塔
function combineTowers(fixedindex,chairId)
    local fixedTowers =findSameFixedindexTowers(fixedindex,chairId)
    if #fixedTowers == 3 then
        local newT = {}
        -- 清空原有塔
        for _, tower in ipairs(towers) do
            if tower.fixedindex ==  fixedindex  and tower.side == chairId then
                -- table.remove(towers, _) -- 删除塔 删除元素前移动 导致删除不了所有元素
            else
                table.insert(newT , tower)
            end
           
        end
        towers= newT
         -- 测试功能 暂时只是编号1的塔升级成编号2
        local newtower  =FlameTower:new(fixedTowers[1].x, fixedTowers[1].y, fixedTowers[1].side, fixedTowers[1].fixedindex)
        table.insert(towers, newtower)
        -- newtower:upgrade()  -- 提升新塔的属性
    end
end
-- 找出同类型没满的塔 的地图编号
function findMinSameTypeTowers(towerType)
    local fixedTowers,fixedTowersType = getFixedTowers()
    for k, v in ipairs(fixedTowersType) do
        if v  == towerType and fixedTowers[k] <3 then
            return k
        end
    end
    for m, n in ipairs(fixedTowers) do
        if n ==0 then
            return m
        end
    end
    return 0
end
-- 统计固定位置的相同类型塔的数量
function getFixedTowers()
    -- 他放置的16个位置
    local  tempFixedarray = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    local  tempFixedTowerType = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    for _, tower in ipairs(towers) do
        tempFixedarray[tower.fixedindex] = tempFixedarray[tower.fixedindex] +1
        tempFixedTowerType[tower.fixedindex] = tower.towerType
    end
    return tempFixedarray,tempFixedTowerType
end
-- 找出空的最小编号固定位置的塔
function findEmptyFixedTowers()
    -- 估计位置
    local fixedTowers = getFixedTowers()
    for k, v in ipairs(fixedTowers) do
        if v ==0 then
            return v
        end
    end
    return 0
end
-- 找出最小没满的固定位置的塔
function findEmptyFixedTowers()
    -- 估计位置
    local fixedTowers = getFixedTowers()
    for k, v in ipairs(fixedTowers) do
        if v ==0 then
            return v
        end
    end
    return 0
end
-- 临时方法  正式环境不需要
function clone(object)
    local lookup_table = {}
    local function _copy(object)
        if type(object) ~= "table" then
            return object
        elseif lookup_table[object] then
            return lookup_table[object]
        end
        local new_table = {}
        lookup_table[object] = new_table
        for key, value in pairs(object) do
            new_table[_copy(key)] = _copy(value)
        end
        return setmetatable(new_table, getmetatable(object))
    end
    return _copy(object)
end

-- 更新火焰弹
function updateFireballs(dt, enemies)
    for i = #fireballs, 1, -1 do
        local fireball = fireballs[i]
        fireball:update(dt,fireAreas)
        if not fireball:isAlive() then
            fireball:explode(enemies,fireAreas)  -- 爆炸并造成伤害
            table.remove(fireballs, i)  -- 移除火焰弹
        end
    end
end
-- 更新火焰区域 持续伤害
function updateFireAreas(dt, enemies)
    -- dt =1
    for i = #fireAreas, 1, -1 do
        local fireArea = fireAreas[i]
        if not fireArea:update(dt, enemies) then
            table.remove(fireAreas, i)  -- 移除过期火焰区域
        end
    end
end
-- 游戏主循环
function gameLoop()
end